package com.yc.yyds.servlet;

import com.google.gson.Gson;
import com.yc.yyds.dao.UserQueryMoviesDao;
import com.yc.yyds.util.DBHelper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "QueryMovieServlet", value = "/QueryMovieServlet.s")
public class QueryMovieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        final String pageSize = request.getParameter("pageSize");
        final String currentPage = request.getParameter("currentPage");

        String moviename = request.getParameter("moviename");
        String moviedate = request.getParameter("moviedate");
        String area = request.getParameter("area");
        String type = request.getParameter("type");
        int size = Integer.valueOf(pageSize);
        int page = Integer.valueOf(currentPage);
        int begin = size * (page - 1);

        String sql = "select * from movie where status=1 ";

        List<Object> params=new ArrayList<>();
        if(moviename !=null && !moviename.trim().isEmpty()){
            sql+=" and moviename like ?";
            params.add("%"+moviename+"%");
        }
        if (moviedate!=null && !moviedate.trim().isEmpty()){
            sql+= " and moviedate like ?";
            params.add("%"+moviedate+"%");
        }
        if (area!=null && !area.trim().isEmpty()){
            sql+= " and area like ?";
            params.add("%"+area+"%");
        }
        if (type!=null && !type.trim().isEmpty()){
            sql+= " and type like ?";
            params.add("%"+type+"%");
        }

        // 查询总行数
        final long total = DBHelper.count(sql,params.toArray());
        params.add(begin);
        params.add(size);

        // 查询当前页的数据
        final List<Map<String, Object>> data =
                DBHelper.selectListMap(sql + " limit ?, ?", params.toArray());

        Map<String, Object> result = new HashMap<>();
        result.put("data",data);
        result.put("total",total);
        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
